<template>
  <div>
    <n-modal
      v-model:show="showModal"
      :mask-closable="false"
      :show-icon="false"
      preset="dialog"
      transform-origin="center"
      :title="formValue.id > 0 ? '编辑租户套餐表 #' + formValue.id : '添加租户套餐表'"
      :style="{
        width: dialogWidth,
      }"
    >
      <n-scrollbar style="max-height: 87vh" class="pr-5">
        <n-spin :show="loading" description="请稍候...">
          <n-form
            ref="formRef"
            :model="formValue"
            :rules="rules"
            :label-placement="settingStore.isMobile ? 'top' : 'left'"
            :label-width="100"
            class="py-4"
          >
            <n-grid cols="1 s:1 m:1 l:1 xl:1 2xl:1" responsive="screen">
              <n-gi span="1">
                <n-form-item label="套餐名" path="name">
                  <n-input placeholder="请输入套餐名" v-model:value="formValue.name" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="租户状态" path="status">
                  <n-select
                    v-model:value="formValue.status"
                    :options="dict.getOptionUnRef('sys_normal_disable')"
                  />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="备注" path="remark">
                  <n-input type="textarea" placeholder="备注" v-model:value="formValue.remark" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="菜单权限" path="menuIds">
                  <template v-if="loading">
                    <div class="flex items-center justify-center py-4">
                      <n-spin size="medium" />
                    </div>
                  </template>
                  <template v-else>
                    <n-tree-select
                      v-model:value="formValue.menuIds"
                      block-line
                      cascade
                      checkable
                      multiple
                      key-field="id"
                      :virtual-scroll="true"
                      :options="treeOption"
                      style="max-height: 650px; overflow: hidden"
                    />
                    <!--                          :expandedKeys="expandedKeys"-->
                    <!--                          @update:selected-keys="selectedTree"-->
                    <!--                          @update:expanded-keys="onExpandedKeys"-->
                  </template>
                </n-form-item>
              </n-gi>
            </n-grid>
          </n-form>
        </n-spin>
      </n-scrollbar>
      <template #action>
        <n-space>
          <n-button @click="closeForm"> 取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm"> 确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, onMounted } from 'vue';
  import { useDictStore } from '@/store/modules/dict';
  import { Edit, View } from '@/api/sysTenantPackage';
  import { State, newState, rules } from './model';
  import { useProjectSettingStore } from '@/store/modules/projectSetting';
  import { useMessage } from 'naive-ui';
  import { adaModalWidth } from '@/utils/hotgo';
  import { getMenuList } from '@/api/system/menu';
  import { loadOptions } from '@/views/permission/menu/model';

  const emit = defineEmits(['reloadTable']);
  const message = useMessage();
  const settingStore = useProjectSettingStore();
  const dict = useDictStore();
  const loading = ref(false);
  const showModal = ref(false);
  const formValue = ref<State>(newState(null));
  const formRef = ref<any>({});
  const formBtnLoading = ref(false);
  const treeOption = ref([]);
  const dialogWidth = computed(() => {
    return adaModalWidth(840);
  });

  // function onExpandedKeys(keys) {
  //   expandedKeys.value = keys;
  // }
  //
  // function selectedTree(keys: number[], option: any[]) {
  //   let item = null;
  //   if (keys.length) {
  //     item = option[0];
  //   }
  //   formParams.value = newState(item);
  // }

  // 提交表单
  function confirmForm(e) {
    e.preventDefault();
    formRef.value.validate((errors) => {
      if (!errors) {
        formBtnLoading.value = true;
        Edit(formValue.value)
          .then((_res) => {
            message.success('操作成功');
            closeForm();
            emit('reloadTable');
          })
          .finally(() => {
            formBtnLoading.value = false;
          });
      } else {
        message.error('请填写完整信息');
      }
    });
  }

  // 关闭表单
  function closeForm() {
    showModal.value = false;
    loading.value = false;
  }

  // 打开模态框
  function openModal(state: State) {
    showModal.value = true;

    // 新增
    if (!state || state.id < 1) {
      formValue.value = newState(state);

      return;
    }

    // 编辑
    loading.value = true;
    View({ id: state.id })
      .then((res) => {
        formValue.value = { ...res, menuIds: JSON.parse(res.menuIds) };
      })
      .finally(() => {
        loading.value = false;
      });
  }

  // 加载菜单选项树
  function loadTreeOption() {
    const needLoading = treeOption.value.length == 0;
    if (needLoading) {
      loading.value = true;
    }

    getMenuList()
      .then((res) => {
        if (res.list && res.list.length > 0) {
          treeOption.value = res.list;
        } else {
          treeOption.value = [];
        }
      })
      .finally(() => {
        if (needLoading) {
          loading.value = false;
        }
      });
  }

  onMounted(() => {
    loadTreeOption();
    loadOptions();
  });

  defineExpose({
    openModal,
  });
</script>

<style lang="less"></style>
